﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using MYTech.Utils;

namespace MYTech.IO
{
    /// <summary>
    /// Csv文件帮助类
    /// </summary>
    public class CsvHelper
    {
        /// <summary>
        /// 保存DataTable到指定的路径
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="filePath"></param>
        public static void Save(DataTable dataTable, string filePath)
        {
            string[] cols = new string[dataTable.Columns.Count];
            for (int i = 0; i < cols.Length; ++i)
                cols[i] += dataTable.Columns[i].ColumnName;
            Save(dataTable, string.Join(",", cols), filePath);
        }

        /// <summary>
        /// 保存DataTable到指定的路径
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="columns"></param>
        /// <param name="filePath"></param>
        public static void Save(DataTable dataTable, string columns, string filePath)
        {
            using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.Default, 128 * 1024))
            {
                sw.WriteLine(columns);
                string[] cols = new string[dataTable.Columns.Count];
                foreach (DataRow row in dataTable.Rows)
                {
                    for (int i = 0; i < cols.Length; ++i)
                        cols[i] = row.ItemArray[i].ToString();
                    sw.Write('\"');
                    sw.Write(string.Join("\",\"", cols));
                    sw.Write("\"\n");
                }
                sw.Close();
            }
        }

        /// <summary>
        /// 保存DataTable的前rowcount行到指定的路径
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="rowCount"></param>
        /// <param name="columns"></param>
        /// <param name="filePath"></param>
        public static void Save(DataTable dataTable, int rowCount, string columns, string filePath)
        {
            using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.Default, 128 * 1024))
            {
                sw.WriteLine(columns);
                string[] cols = new string[dataTable.Columns.Count];
                foreach (DataRow row in dataTable.Rows)
                {
                    if (rowCount-- == 0)
                        break;
                    for (int i = 0; i < cols.Length; ++i)
                        cols[i] = row.ItemArray[i].ToString();
                    sw.Write('\"');
                    sw.Write(string.Join("\",\"", cols));
                    sw.Write("\"\n");
                }
                sw.Close();
            }
        }

        /// <summary>
        /// 保存DataRow行到指定的路径
        /// </summary>
        /// <param name="rows"></param>
        /// <param name="rowCount"></param>
        /// <param name="columnCount"></param>
        /// <param name="columns"></param>
        /// <param name="filePath"></param>
        public static void Save(DataRow[] rows, int rowCount, int columnCount, string columns, string filePath)
        {
            using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.Default, 128 * 1024))
            {
                sw.WriteLine(columns);
                string[] cols = new string[columnCount];
                foreach (DataRow row in rows)
                {
                    if (rowCount-- == 0)
                        break;
                    for (int i = 0; i < cols.Length; ++i)
                        cols[i] = row.ItemArray[i].ToString();
                    sw.Write('\"');
                    sw.Write(string.Join("\",\"", cols));
                    sw.Write("\"\n");
                }
                sw.Close();
            }
        }

        /// <summary>
        /// 保存行到指定的路径
        /// </summary>
        /// <param name="rows"></param>
        /// <param name="columns"></param>
        /// <param name="filePath"></param>
        /// <param name="encoding"></param>
        public static void Save(List<string> rows, string columns, string filePath, Encoding encoding)
        {
            using (StreamWriter sw = new StreamWriter(filePath, false, encoding, 128 * 1024))
            {
                if (!string.IsNullOrEmpty(columns))
                    sw.WriteLine(columns);
                foreach (string row in rows)
                {
                    sw.WriteLine(row);
                }
                sw.Close();
            }
        }

        /// <summary>
        /// 导入csv文件到内存
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static DataTable Load(string filePath)
        {
            return Load(filePath, Encoding.Default);
        }

        /// <summary>
        /// 导入csv文件到内存
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static DataTable Load(string filePath, Encoding encoding)
        {
            return Load(filePath, null, encoding);
        }

        /// <summary>
        /// 导入csv文件到内存，并报告进度
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="report"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static DataTable Load(string filePath, ReportProgressStatus report, Encoding encoding)
        {
            string[] iRows = null;
            string[] iCols = null;
            string cellContent = "";
            int errorIndex = 0;
            try
            {
                if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
                {
                    DataTable dt = new DataTable();
                    using (StreamReader _Reader = new StreamReader(filePath, encoding))
                    {
                        string content = _Reader.ReadToEnd();
                        iRows = content.Split(new string[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);
                        if (report != null)
                            report("开始整理数据...");
                        for (int iRow = 0; iRow < iRows.Length; iRow++)
                        {
                            errorIndex++;
                            iCols = iRows[iRow].Split(new Char[] { ',' });
                            DataRow dr = dt.NewRow();
                            for (int iCol = 0; iCol < iCols.Length; iCol++)
                            {
                                cellContent = iCols[iCol];
                                if (iRow == 0)
                                    dt.Columns.Add(cellContent.Replace("\"", ""));
                                else
                                    dr[iCol] = cellContent.Replace("\"", "");
                            }
                            if (iRow != 0)
                                dt.Rows.Add(dr);
                        }
                        _Reader.Close();
                        if (report != null)
                            report(string.Format("导入结束，共导入{0}条数据...", dt.Rows.Count));
                        return dt;
                    }
                }
            }
            catch (Exception ex)
            {
                if (report != null)
                    report(string.Format("{0}:在{1}行处出现异常...", ex.Message, errorIndex));
            }
            return null;
        }
    }
}


